import os
import re
import time
from asyncio import sleep
import pikepdf
import PyPDF2
import telebot
from telebot import types
import threading
import datetime
from PyPDF2 import PdfReader, PdfWriter
from llm_response.llm_response import ask_llm, ask_llm_re_country_name, ask_llm_re_password, ask_llm_re_passw, \
    ask_llm20_1, ask_llm_result, ask_qwen_img_utr, ask_qwen_video_utr, ask_llm_qwen3
from uitls.customer_type.chargeback.dispute import order_retrieval
from uitls.customer_type.open_success_rate.large_plate_success_rate.large_succ_rate import large_succ_rate
from uitls.customer_type.open_success_rate.success_rate.succ_rate import open_success_rate
from uitls.customer_type.order_money.is_or_not_receive_moeny import receive_money
from uitls.customer_type.payout.payout_succession.payout_is_or_not_success import payout_is_or_not_succession
from uitls.customer_type.payout_correction.payout_reversal import payout_correction
from uitls.customer_type.payout_voucher.payment_voucher import disbursement_voucher
from uitls.customer_type.reject.overrule.dismiss import dismiss
from uitls.customer_type.reversal import payout_reversal, payout_reversal_anim, payout_reversal_photos
from uitls.customer_type.urgent_payout.expedited_payout import exp_payout
from uitls.customer_type.utr_extraction.select_utr_by_order import select_utr_by_order
from uitls.customer_type.utr_extraction.utr_correspond_order.select_order_by_utr import select_order_by_utr
from uitls.customer_type.va_pay.va_payment import va_payment_status
from uitls.parse.parse_order import parse_order_ids
from uitls.re_extraction import re_exr, re_exr_file, re_exr_operation_people, payout_wallet_account_mobile_number, \
    internal_deposit_u_address, new_merchant_login_dashboard, simulated_payout, merchant_key_reset, \
    test_environment_collection_callback,  indonesian_commands, indian_commands, \
    bangladesh_commands, pakistan_commands
from uitls.reqquests_post import get_payment_inquiry_img, get_payment_inquiry_pdf, get_payment_inquiry_openmakeup
import redis
import json

# Bot Token
TOKEN = '7702930752:AAGYV0-kGJgMTavSPKxqdgo8tkR_gdthYJI'
bot = telebot.TeleBot(TOKEN)

# 连接本地 Redis（默认端口 6379）
r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='yb@123456')
# r = redis.Redis(host='127.0.0.1', port=6379, db=0, password=None)

# 获取机器人的用户名（比如 bot 的 username 是 mytestbot）
bot_username = 'zynth_core_bot'  # 不要带 @，直接写用户名

media_cache = {}
media_timers = {}


def save_file(save_dir, file_id, filename=None):
    # 获取文件信息
    file_info = bot.get_file(file_id)
    downloaded_file = bot.download_file(file_info.file_path)
    if not filename:
        filename = os.path.basename(file_info.file_path)
    save_path = os.path.join(save_dir, filename)
    with open(save_path, 'wb') as f:
        f.write(downloaded_file)
    print(f"✅ 已保存文件: {save_path}")
    return save_path


# /start 命令处理器
@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, "你好，欢迎使用这个 Bot！")


# 文本消息
@bot.message_handler(func=lambda message: True)
def handle_text(message):
    user = message.from_user.first_name
    text = message.text
    chat_id = message.chat.id
    print("message.chat.id", message.chat.id)
    country_name = ask_llm_re_country_name(message.chat.title)
    try:
        country_name_address = json.loads(country_name)
    except json.JSONDecodeError:
        print("不是 JSON，原始输出：", country_name)
        country_name_address = {"address": "", "mid": ""}  # 兜底，直接包一层
    print(f"[文本] 来自 {user} ({chat_id}): {text}")
    if country_name_address['address'] != "":
        if message.chat.type in ["group", "supergroup"]:
            # 群组中，判断是否 @ 了机器人
            if f"@{bot_username}" in message.text:
                if len(message.text) == 15:
                    bot.reply_to(message, "你 @ 了我，我来了～ 我有什么可以帮助你的吗 🤖")
                else:
                    clean_text = re.sub(r'^@\w+\s*', '', text)
                    llm_res = ask_llm(clean_text)
                    result = re_exr(llm_res, clean_text, country_name_address, message)
                    if llm_res != '无' and result != "":
                        bot.reply_to(message, result)
                    else:
                        res = re_exr_operation_people()
                        if res == "":
                            print("无")
                        else:
                            bot.reply_to(message, res)
            else:
                llm_resp = ask_llm(text)
                if llm_resp != '' and llm_resp == '3':
                    print("加急")
                    exp_payout(country_name_address, message)
                elif llm_resp != '' and llm_resp == '4':
                    disbursement_voucher(country_name_address, message)
                elif llm_resp != '' and llm_resp == '8':
                    print("8代收成功率怎么样")
                    open_success_rate(country_name_address, message)
                elif llm_resp != '' and llm_resp == '9':
                    print("代付冲正了吗")
                    payout_correction(country_name_address, message)
                elif llm_resp != '' and llm_resp == '17':
                    print("代付驳回")
                    dismiss(country_name_address, message)
                elif llm_resp != '' and llm_resp == '18':
                    print("代收怎么掉单这么严重？")
                    order_retrieval(message)
                elif llm_resp != '' and llm_resp == '19':
                    print("VA返回的付款碼，您那邊一般是怎麼呈現?")
                    va_payment_status(message)
                elif llm_resp != '' and llm_resp == '20':
                    print("代付钱包账号和手机号是一样的吗？")
                    payout_wallet_account_mobile_number(message)
                elif llm_resp != '' and llm_resp == '21':
                    print("需要内充及更换提U地址")
                    internal_deposit_u_address(message)
                elif llm_resp != '' and llm_resp == '22':
                    print("新商户登录后台，没有弹出谷歌二维码绑定，如何解决？")
                    new_merchant_login_dashboard(message)
                elif llm_resp != '' and llm_resp == '23':
                    if country_name_address['address'] == "https://adm.deepaym.com":
                        print("有办法模拟代付吗？")
                        simulated_payout(message)
                    else:
                        print("没有输出")
                elif llm_resp != '' and llm_resp == '24':
                    print("商户密钥是一定需要重置的是吗？")
                    merchant_key_reset(message)
                elif llm_resp != '' and llm_resp == '25':
                    if country_name_address['address'] == "https://admpkr.deepay.ink":
                        print("测试环境代收回调问题")
                        test_environment_collection_callback(message)
                    else:
                        print("测试环境代收回调问题")
                elif llm_resp != '' and llm_resp == '26':
                    print("印尼指令")
                    indonesian_commands(message)
                elif llm_resp != '' and llm_resp == '27':
                    print("印度指令")
                    indian_commands(message)
                elif llm_resp != '' and llm_resp == '28':
                    print("孟加拉指令")
                    bangladesh_commands(message)
                elif llm_resp != '' and llm_resp == '29':
                    print("巴基斯坦指令")
                    pakistan_commands(message)
                elif llm_resp != '' and llm_resp == '30':
                    print("251027YW9B167E0096420239 流水号utr提供下")
                    select_utr_by_order(country_name_address, message)
                elif llm_resp != '' and llm_resp == '31':
                    print("d2072510270356586160399 这笔代付成功了吗")
                    payout_is_or_not_succession(country_name_address, message)
                elif llm_resp != '' and llm_resp == '32':
                    print("481094464396这个utr对应单号是")
                    select_order_by_utr(message)
                elif llm_resp != '' and llm_resp == '33':
                    print("s082510250952358558062 帮查下，这笔有没有收到钱的")
                    receive_money(country_name_address, message)
                elif llm_resp != '' and llm_resp == '34':
                    print("大盘成功率")
                    large_succ_rate(country_name_address, message)
                elif llm_resp == '无':
                    print("闲聊功能")
                    llm_resp = ask_llm_qwen3(text)
                    print("闲聊回答：",llm_resp)
                    bot.reply_to(message, llm_resp)
                else:
                    print("llm_resp", llm_resp)
                    res1 = re_exr(llm_resp, text, country_name_address, message)
                    print("res1res1", res1)
                    if llm_resp != '无' and res1 != "":
                        bot.reply_to(message, res1)
                    else:
                        print("没有输出")
        else:
            # 私聊中，直接回复1
            bot.reply_to(message, "你好，我是机器人！")
    else:
        """
            判断消息是回复了某条消息，还是@了某个人 12
            返回:
                dict 包含:
                    - reply_text: 被回复的原始消息文本 (如果有)
                    - mentions: 在正文里 @ 的用户名列表 (如果有)
            """
        print("message", message)

        # 1. 是否回复了消息
        if hasattr(message, "reply_to_message") and message.reply_to_message:
            print("回复上游内容")
            if message.reply_to_message.caption is not None:
                order_ids = ask_llm20_1(message.reply_to_message.caption)
                order_ids_data = parse_order_ids(order_ids)
                if order_ids_data['order_ids']:
                    print("订单号不是空的")
                    raw = r.get(order_ids_data['order_ids'][0])
                    if raw:
                        data = json.loads(raw)
                        bot.send_message(data["chat_id"], f"单号：{data['order_id']},{text}",
                                         reply_to_message_id=data["message_id"])
            elif message.reply_to_message.text is not None:
                order_ids = ask_llm20_1(message.reply_to_message.text)
                order_ids_data = parse_order_ids(order_ids)
                if order_ids_data['order_ids']:
                    print("订单号不是空的")
                    raw = r.get(order_ids_data['order_ids'][0])
                    if raw:
                        data = json.loads(raw)
                        bot.send_message(data["chat_id"], f"单号：{data['order_id']},{text}",
                                         reply_to_message_id=data["message_id"])
            else:
                print("redis没有找到值")


# 文件（document)
@bot.message_handler(content_types=['document'])
def handle_document(message):
    user = message.from_user.first_name
    chat_id = message.chat.id
    file_id = message.document.file_id
    filename = message.document.file_name
    text = message.caption
    print("message.chat.title", message.chat.title)
    country_name = ask_llm_re_country_name(message.chat.title)
    try:
        data_address = json.loads(country_name)
    except json.JSONDecodeError:
        print("不是 JSON，原始输出：", country_name)
        data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
    print("data_address", data_address)
    if country_name != "无":
        if text is not None:
            print("text", text)
            order_ids = ask_llm20_1(text)
            print("order_id:", order_ids)
            order_data_ids = parse_order_ids(order_ids)
            if order_data_ids["order_ids"]:
                data_payoutOrder = get_payment_inquiry_pdf(data_address, order_data_ids['order_ids'][0])
                print("data_payoutOrder", data_payoutOrder)
                try:
                    parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
                except json.JSONDecodeError:
                    print("不是 JSON，原始输出：", data_payoutOrder)
                    parsed = {"status": 201}  # 先把 JSON 字符串转成字典

                if parsed['status'] == 200:
                    length_payout = len(parsed["data"]['orderInfo']['payoutSourceOrders'])
                    print("length_payout", length_payout)

                    order_ref = parsed["data"]['orderInfo']['payoutSourceOrders'][length_payout - 1]['order_ref']
                    #  提取上游订单号order_ref

                    # print("order_ref",parsed["data"]['orderInfo']['payoutSourceOrders'][1]['order_ref'])  # 再取 "data" 键
                    telegram_group = parsed["data"]['orderInfo']['channel']['telegram_group']
                    print("telegram_group", parsed["data"]['orderInfo']['channel']['telegram_group'])  # 再取 "data" 键

                    if data_address['address'] != "":
                        print("data", data_address)
                        # data=json.loads('{"address":"https://adm-test.deepaym.com","mid":"1010"}')
                        print("data", data_address)
                        # 生成时间戳字符串，例如：20250814143055（年月日时分秒）
                        timestamp = time.strftime("%Y%m%d%H%M%S")
                        # 保存路径
                        # save_dir = 'D:\\yuanbei\\客服问答机器人需求表\\source_files\\pdfs\\undecrypted_pdfs\\'
                        save_dir = '/home/admin/data/data/aicustomer-service/source_files/pdfs/undecrypted_pdfs'
                        # os.makedirs(save_dir, exist_ok=True)

                        input_path = save_file(save_dir, file_id, filename)

                        # output_path = rf"D:\\yuanbei\\客服问答机器人需求表\\source_files\\pdfs\\decrypted_pdfs\\{timestamp}.pdf"
                        output_path = rf"/home/admin/data/data/aicustomer-service/source_files/pdfs/decrypted_pdfs/{timestamp}.pdf"

                        #
                        print("output_path", output_path)

                        llm_pass = ask_llm_re_password(filename)
                        llm_passw = ask_llm_re_passw(text)
                        print("llm_pass", llm_pass)
                        print("llm_passw", llm_passw)

                        if llm_pass != "空":
                            password = llm_pass
                            print("pass", password)
                        else:
                            password = llm_passw
                            print("pass", password)

                        sleep(21)
                        try:
                            print("input_path", input_path)
                            reader = PdfReader(input_path)
                            print("reader", reader)
                            # 首先尝试用 PyPDF2 打开
                            with open(input_path, "rb") as f:
                                reader = PyPDF2.PdfReader(f)
                                if reader.is_encrypted:
                                    print("PDF 已加密，尝试解密...")
                                    # 如果提供密码
                                    if password:
                                        if reader.decrypt(password):
                                            print("解密成功1")
                                            writer = PdfWriter()
                                            for page in reader.pages:
                                                writer.add_page(page)
                                            with open(output_path, "wb") as f:
                                                writer.write(f)
                                            print("解密完成1:", output_path)
                                            result = re_exr_file(output_path, data_payoutOrder)
                                            if result is not None:
                                                bot.reply_to(message, result)
                                                # 群聊 ID（比如 -1001234567890）
                                                # group_chat_id = -4805059187
                                                group_chat_id = telegram_group
                                                # 发送 PDF
                                                res = ask_llm_result(result)
                                                if res == 'y':
                                                    # 发送 PDF
                                                    data1 = {
                                                        "chat_id": message.chat.id,
                                                        "message_id": message.message_id,
                                                        "order_id": order_data_ids['order_ids'][0]
                                                    }
                                                    r.set(order_ref, json.dumps(data1), ex=3600)
                                                    with open(output_path, 'rb') as pdf_file:
                                                        bot.send_document(group_chat_id, pdf_file,
                                                                          caption=f'''
                                                                密码：{password}，\n订单号：{order_ref}，\n请核查代付冲正
                                                                 ''')
                                                else:
                                                    print("不符合")
                                            else:
                                                print("没有输出")
                                        else:
                                            print("密码不正确，尝试 pikepdf 解密...")
                                            # 尝试用 pikepdf 解密
                                            with pikepdf.open(input_path, password=password) as pdf:
                                                print("pikepdf 解密成功")
                                                writer = PdfWriter()
                                                for page in reader.pages:
                                                    writer.add_page(page)
                                                with open(output_path, "wb") as f:
                                                    writer.write(f)
                                                print("解密完成:", output_path)
                                            print("密码错误，无法解密")
                                            result = re_exr_file(output_path, data_payoutOrder)
                                            if result is not None:
                                                data1 = {
                                                    "chat_id": message.chat.id,
                                                    "message_id": message.message_id,
                                                    "order_id": order_data_ids['order_ids'][0]
                                                }
                                                r.set(order_ref, json.dumps(data1), ex=3600)
                                                bot.reply_to(message, result)
                                                # 群聊 ID（比如 -1001234567890）
                                                group_chat_id = telegram_group
                                                res = ask_llm_result(result)
                                                if res == 'y':
                                                    if password == "":
                                                        print("没有密码")
                                                        with open(output_path, 'rb') as pdf_file:
                                                            bot.send_document(group_chat_id, pdf_file,
                                                                              caption=f'''
                                                            密码：{"无"}，\n订单号：{order_ref}，\n请核查代付冲正
                                                            ''')
                                                    else:
                                                        print("有密码")
                                                        with open(output_path, 'rb') as pdf_file:
                                                            bot.send_document(group_chat_id, pdf_file,
                                                                              caption=f'''
                                                            密码：{password}，\n订单号：{order_ref}，\n请核查代付冲正
                                                            ''')
                                                else:
                                                    print("不符合")
                                            else:
                                                print("没有输出")
                                else:
                                    # 如果没加密或已解密
                                    writer = PdfWriter()
                                    for page in reader.pages:
                                        writer.add_page(page)
                                    with open(output_path, "wb") as f:
                                        writer.write(f)
                                    result = re_exr_file(output_path, data_payoutOrder)
                                    if result is not None:
                                        data1 = {
                                            "chat_id": message.chat.id,
                                            "message_id": message.message_id,
                                            "order_id": order_data_ids['order_ids'][0]
                                        }
                                        r.set(order_ref, json.dumps(data1), ex=3600)
                                        bot.reply_to(message, result)
                                        # 群聊 ID（比如 -1001234567890）
                                        group_chat_id = telegram_group
                                        res = ask_llm_result(result)

                                        if res == 'y':
                                            if password == "":
                                                print("没有密码")
                                                with open(output_path, 'rb') as pdf_file:
                                                    bot.send_document(group_chat_id, pdf_file,
                                                                      caption=f'''
                                                    密码：{"无"}，\n订单号：{order_ref}，\n请核查代付冲正
                                                    ''')
                                            else:
                                                print("有密码")
                                                with open(output_path, 'rb') as pdf_file:
                                                    bot.send_document(group_chat_id, pdf_file,
                                                                      caption=f'''
                                                    密码：{password}，\n订单号：{order_ref}，\n请核查代付冲正
                                                    ''')
                                        else:
                                            print("不符合")

                                # else:
                                #     print("没有输出")
                        except Exception as e:
                            bot.reply_to(message, "请重新提供密码,你的密码错误或者无效的密码")
                            print("读取 PDF 出错:", e)
                        print(f"[文件] 来自 {user} ({chat_id}): 文件名 = {filename}")
                        # llm_r = ask_llm(text)
                    else:
                        print("群聊错误")
                else:
                    bot.reply_to(message, "订单查询不成功,请检查订单号，商户号，是否和国家对应")
                    print("订单查询不成功")
            else:
                bot.reply_to(message, "该订单号为空")
        else:
            print("文本为空。直接打开pdf，打不开则缓")
    else:
        print("ok")


def process_group(group_id):
    """定时处理同一 media_group 的消息"""
    group = media_cache.pop(group_id, None)
    if not group:
        return
    photos = group.get("photos", [])
    videos = group.get("videos", [])
    animations = group.get("animations", [])

    timestamp = time.strftime("%Y%m%d%H%M%S")

    if photos and videos:
        saved_imgs = []
        saved_vids = []

        saved_vids_file_id = []
        saved_imgs_file_id = []
        message = photos[0]
        for pho in photos:
            if pho.content_type == "photo":
                file_id = pho.photo[-1].file_id
                saved_imgs_file_id.append(file_id)
                filename = f"{timestamp}_img.jpg"
                save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/imgs"
                # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\imgs"
                path_img = save_file(save_dir, file_id, filename)
                if path_img:
                    saved_imgs.append(path_img)
                    print(f"✅ 保存图片: {path_img}")
        for vid in videos:
            message_videos = videos[0]
            if vid.content_type == "video":
                file_id = vid.video.file_id
                saved_vids_file_id.append(file_id)
                # 存数据库/字典
                filename = f"{timestamp}_viedo.mp4"
                save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/videos"
                # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\videos"
                file_info = message_videos.video
                if file_info.file_size > 20 * 1024 * 1024:
                    print("视频文件过大，无法下载，请换文件下载")
                else:
                    path_vid = save_file(save_dir, file_id, filename)
                    if path_vid:
                        saved_vids.append(path_vid)
                        print(f"✅ 保存视频: {path_vid}")

        country_name = ask_llm_re_country_name(videos[0].chat.title)
        print("country_name", country_name)
        try:
            data_address = json.loads(country_name)
        except json.JSONDecodeError:
            print("不是 JSON，原始输出：", country_name)
            data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
        sleep(21)

        if videos[0].caption:
            text = videos[0].caption
        else:
            text = photos[0].caption
        print("text", text)
        print("data_address", data_address)
        order_ids = ask_llm20_1(text)
        order_data_ids = parse_order_ids(order_ids)

        print("order_id:", order_data_ids)
        data_payoutOrder = get_payment_inquiry_img(data_address, order_data_ids['order_ids'][0])
        print("data_payoutOrder", data_payoutOrder)
        try:
            parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
        except json.JSONDecodeError:
            print("不是 JSON，原始输出：", data_payoutOrder)
            parsed = {"status": 201}  # 先把 JSON 字符串转成字典

        img_utr = ask_qwen_img_utr(saved_imgs[0])
        if img_utr is not None:
            data1 = {
                "chat_id": message.chat.id,
                "message_id": message.message_id,
            }
            r.set("1", json.dumps(data1), ex=3600)

        if data_address['address'] != "":
            if parsed['status'] == 200:
                order_sn = parsed['data']['orderInfo']['order_sn']
                trade_sn = parsed['data']['orderInfo']['trade_sn']
                amount = parsed['data']['orderInfo']['amount']
                timestamp = parsed['data']['orderInfo']['instime']
                img_utr = ask_qwen_img_utr(saved_imgs[0])
                # vid_utr = ask_qwen_video_utr(saved_vids[0])
                dt = datetime.datetime.fromtimestamp(timestamp)
                order_time = dt.strftime("%Y/%m/%d %H:%M:%S")
                print("utr", img_utr)
                if parsed['data']['orderInfo']['status'] == 1 or parsed['data']['orderInfo']['status'] == 3:
                    bot.reply_to(message,
                                 f'''成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}'''
                                 )
                    print("成功的无需补单操作")
                else:
                    make_up_order = json.loads(
                        get_payment_inquiry_openmakeup(data_address, order_data_ids['order_ids'][0], img_utr))
                    print("make_up_order", make_up_order)
                    print("utr", img_utr)
                    l = len(parsed['data']['orderInfo']['sourceOrders'])
                    if make_up_order['status'] == 200:
                        bot.reply_to(message,
                                     f'''订单补单成功\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"订单补单成功"}\n订单时间:{order_time}'''
                                     )
                        print("订单补单成功")
                    if make_up_order['status'] == 17510:
                        bot.reply_to(message,
                                     f'''订单状态错误\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"订单状态错误"}\n订单时间:{order_time}'''
                                     )
                        print("订单状态错误")
                    if make_up_order['status'] == 17511:
                        bot.reply_to(message,
                                     f'''SYSTEM_EXCEPT_ERROR\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"SYSTEM_EXCEPT_ERROR"}\n订单时间:{order_time}'''
                                     )
                        print("SYSTEM_EXCEPT_ERROR")
                    if make_up_order['status'] == -2:
                        bot.reply_to(message,
                                     f'''查询状态为空\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"查询状态为空"}\n订单时间:{order_time}'''
                                     )
                        print("查询状态为空")

                    if l != 0:
                        if make_up_order['status'] == 10001:
                            bot.reply_to(message,
                                         f'''已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"暂未收到"}\n订单时间:{order_time}'''
                                         )
                            # 发送图片
                            upstream = parsed['data']['orderInfo']['sourceOrders'][l - 1]['order_ref']

                            media = [
                                types.InputMediaVideo(media=saved_vids_file_id[0],
                                                      caption=f'''单号：{upstream}\n麻烦核查下是否收到款项，如若未收到，请识别是否是你们的收款账户？'''),
                                # 视频 file_id
                                types.InputMediaPhoto(media=saved_imgs_file_id[0]),  # file_id 2
                            ]

                            # media = [
                            #     types.InputMediaVideo(open(saved_vids_file_id[0], "rb"),
                            #                           caption=f'''单号：{upstream}\n麻烦核查下是否收到款项，如若未收到 请识别是否是你们的收款账户？'''
                            #                           ),
                            #     types.InputMediaPhoto(open(saved_imgs[0], "rb"))
                            # ]
                            try:
                                data1 = {
                                    "chat_id": message.chat.id,
                                    "message_id": message.message_id,
                                    "order_id": order_data_ids['order_ids'][0]
                                }
                                r.set(upstream, json.dumps(data1), ex=2592000)
                                bot.send_media_group(-4805059187,
                                                     media,
                                                     )
                            except Exception as e:
                                print("发送失败，重试中:", e)
                                bot.send_media_group(-4805059187,
                                                     media,
                                                     )
                            print("请联系上游")
                    else:
                        bot.reply_to(message, "没有上游订单号")
                        print("没有上游订单号")
            else:
                bot.reply_to(message, "订单号不正确或者订单号不存在，请重新查看。")
                print("接口调不通，请重新查看接口。")
        else:
            # 1. 是否回复了消息
            if hasattr(message, "reply_to_message") and message.reply_to_message:
                if message.reply_to_message.caption is not None:
                    order_ids = ask_llm20_1(message.reply_to_message.caption)
                    order_ids_data = parse_order_ids(order_ids)
                    raw = r.get(order_ids_data['order_ids'][0])
                    if text is None:
                        text_content = ""
                    else:
                        text_content = text
                    if raw:
                        data = json.loads(raw)
                        bot.send_media_group(data["chat_id"],
                                             saved_imgs_file_id[0],
                                             reply_to_message_id=data["message_id"],
                                             caption=f'''单号：{data['order_id']},{text_content}'''
                                             )
                elif message.reply_to_message.text is not None:
                    order_ids = ask_llm20_1(message.reply_to_message.text)
                    order_ids_data = parse_order_ids(order_ids)
                    raw = r.get(order_ids_data['order_ids'][0])
                    if text is None:
                        text_content = ""
                    else:
                        text_content = text
                    if raw:
                        data = json.loads(raw)
                        bot.send_media_group(data["chat_id"],
                                             saved_imgs_file_id[0],
                                             reply_to_message_id=data["message_id"],
                                             caption=f'''单号：{data['order_id']},{text_content}'''
                                             )
                else:
                    print("redis没有找到值")


    elif photos:
        print("图片输入")
        message = photos[0]
        text = message.caption
        if text is not None:
            print("text",text)
            llm_res = ask_llm(text)
            if llm_res == '9':
                print("代付冲正")
                # 代付冲正
                payout_reversal_photos(message)
            else:
                saved_imgs_file_id = []
                timestamp = time.strftime("%Y%m%d%H%M%S")
                file_id = message.photo[-1].file_id
                saved_imgs_file_id.append(file_id)
                filename = f"{timestamp}_img.jpg"
                save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/imgs"
                # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\imgs"
                save_path = save_file(save_dir, file_id, filename)
                country_name = ask_llm_re_country_name(message.chat.title)
                if country_name != "无":
                    try:
                        data_address = json.loads(country_name)
                    except json.JSONDecodeError:
                        print("不是 JSON，原始输出：", country_name)
                        data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
                    sleep(21)
                    print("data_address", data_address)
                    order_ids = ask_llm20_1(text)
                    order_data_ids = parse_order_ids(order_ids)
                    if order_data_ids['order_ids']:
                        print("订单号不是空的")
                        print("order_id:", order_data_ids['order_ids'][0])
                        data_payoutOrder = get_payment_inquiry_img(data_address, order_data_ids['order_ids'][0])
                        print("data_payoutOrder1", data_payoutOrder)
                        try:
                            if data_payoutOrder is None:
                                parsed = {"status": 201}  # 先把 JSON 字符串转成字典
                            else:
                                parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
                        except json.JSONDecodeError:
                            print("不是 JSON，原始输出：", data_payoutOrder)
                            parsed = {"status": 201}  # 先把 JSON 字符串转成字典
                        img_utr = ask_qwen_img_utr(save_path)
                        print("img_utr+++++++++++++++++++++++++++++++++++++++", img_utr)
                        if data_address['address'] != "":
                            if parsed['status'] == 200:
                                order_sn = parsed['data']['orderInfo']['order_sn']
                                trade_sn = parsed['data']['orderInfo']['trade_sn']
                                amount = parsed['data']['orderInfo']['amount']
                                timestamp = parsed['data']['orderInfo']['instime']
                                img_utr = ask_qwen_img_utr(save_path)
                                dt = datetime.datetime.fromtimestamp(timestamp)
                                order_time = dt.strftime("%Y/%m/%d %H:%M:%S")
                                print("utr", img_utr)
                                if parsed['data']['orderInfo']['status'] == 1 or parsed['data']['orderInfo']['status'] == 3:
                                    bot.reply_to(message, f'''
                                    成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                            ''')
                                    print("成功的无需补单操作")
                                else:
                                    make_up_order = json.loads(
                                        get_payment_inquiry_openmakeup(data_address, order_data_ids['order_ids'][0], img_utr))
                                    print("make_up_order", make_up_order)
                                    print("utr", img_utr)
                                    l = len(parsed['data']['orderInfo']['sourceOrders'])
                                    if make_up_order['status'] == 200:
                                        bot.reply_to(message, f'''
                                        订单补单成功\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"订单补单成功"}\n订单时间:{order_time}
                                                            ''')
                                        print("订单补单成功")
                                    if make_up_order['status'] == 17510:
                                        bot.reply_to(message, f'''
                                        订单状态错误\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"订单状态错误"}\n订单时间:{order_time}
                                                            ''')
                                        print("订单状态错误")
                                    if make_up_order['status'] == 17511:
                                        bot.reply_to(message, f'''
                                        SYSTEM_EXCEPT_ERROR\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"SYSTEM_EXCEPT_ERROR"}\n订单时间:{order_time}
                                                            ''')
                                        print("SYSTEM_EXCEPT_ERROR")
                                    if make_up_order['status'] == -2:
                                        bot.reply_to(message, f'''
                                        已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"暂未收到"}\n订单时间:{order_time}
                                                            ''')
                                        group_chat_id = -4805059187
                                        upstream = parsed['data']['orderInfo']['sourceOrders'][l - 1]['order_ref']
                                        bot.send_photo(group_chat_id,
                                                       saved_imgs_file_id[0],
                                                       caption=f'''单号：{upstream}\n用户反馈没有收到麻烦核查下这笔订单是否退回？'''
                                                       )
                                    if l != 0:
                                        if make_up_order['status'] == 10001:
                                            bot.reply_to(message, f'''
                                            已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{img_utr}\n订单金额：{amount}\n状态：{"暂未收到"}\n订单时间:{order_time}
                                                            ''')
                                            group_chat_id = -4805059187
                                            # 发送图片
                                            upstream = parsed['data']['orderInfo']['sourceOrders'][l - 1]['order_ref']
                                            data1 = {
                                                "chat_id": message.chat.id,
                                                "message_id": message.message_id,
                                                "order_id": order_data_ids['order_ids'][0]
                                            }
                                            r.set(upstream, json.dumps(data1), ex=2592000)
                                            bot.send_photo(group_chat_id,
                                                           saved_imgs_file_id[0],
                                                           caption=f'''单号：{upstream}\n麻烦核查下是否收到款项，如若未收到，请识别是否是你们的收款账户？'''
                                                           )
                                    else:
                                        bot.reply_to(message, "没有上游订单号")
                                        print("没有上游订单号")
                            else:
                                bot.reply_to(message, "订单号不正确或者订单号不存在，请重新查看。")
                                print("接口调不通，请重新查看接口。")
                        else:
                            bot.reply_to(message, "没有提取到国家名称，需要请重新发一下")
                            print("没有提取到国家名称，需要请重新发一下")
                    else:
                        print("订单号不正确或者订单号不存在，请重新查看。")
                        bot.reply_to(message, "订单号不正确或者订单号不存在，请重新查看。")
                else:
                    # 1. 是否回复了消息
                    if hasattr(message, "reply_to_message") and message.reply_to_message:
                        if message.reply_to_message.caption is not None:
                            order_ids = ask_llm20_1(message.reply_to_message.caption)
                            order_ids_data = parse_order_ids(order_ids)
                            raw = r.get(order_ids_data['order_ids'][0])
                            if text is None:
                                text_content = ""
                            else:
                                text_content = text
                            if raw:
                                data = json.loads(raw)
                                bot.send_photo(data["chat_id"],
                                               saved_imgs_file_id[0],
                                               reply_to_message_id=data["message_id"],
                                               caption=f'''单号：{data['order_id']},{text_content}'''
                                               )
                        elif message.reply_to_message.text is not None:
                            order_ids = ask_llm20_1(message.reply_to_message.text)
                            order_ids_data = parse_order_ids(order_ids)
                            raw = r.get(order_ids_data['order_ids'][0])
                            if text is None:
                                text_content = ""
                            else:
                                text_content = text
                            if raw:
                                print("redis获取到的order_id", r.get("order_id"))
                                data = json.loads(raw)
                                bot.send_photo(data["chat_id"],
                                               saved_imgs_file_id[0],
                                               reply_to_message_id=data["message_id"],
                                               caption=f'''单号：{data['order_id']},{text_content}'''
                                               )
                        else:
                            print("redis没有找到值")
        else:
            print("查看是否是回复")
            saved_imgs_file_id = []
            timestamp = time.strftime("%Y%m%d%H%M%S")
            file_id = message.photo[-1].file_id
            saved_imgs_file_id.append(file_id)
            filename = f"{timestamp}_img.jpg"
            save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/imgs"
            # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\imgs"
            save_path = save_file(save_dir, file_id, filename)
            # 1. 是否回复了消息
            if hasattr(message, "reply_to_message") and message.reply_to_message:
                if message.reply_to_message.caption is not None:
                    order_ids = ask_llm20_1(message.reply_to_message.caption)
                    order_ids_data = parse_order_ids(order_ids)
                    raw = r.get(order_ids_data['order_ids'][0])
                    print("获取redis值，图片功能1")
                    if text is None:
                        text_content = ""
                    else:
                        text_content = text
                    if raw:
                        data = json.loads(raw)
                        bot.send_photo(data["chat_id"],
                                       saved_imgs_file_id[0],
                                       reply_to_message_id=data["message_id"],
                                       caption=f'''单号：{data['order_id']},{text_content}'''
                                       )
                elif message.reply_to_message.text is not None:
                    order_ids = ask_llm20_1(message.reply_to_message.text)
                    order_ids_data = parse_order_ids(order_ids)
                    raw = r.get(order_ids_data['order_ids'][0])
                    print("获取redis中的raw2为",raw)
                    print("获取redis值，图片功能2")
                    if text is None:
                        text_content = ""
                    else:
                        text_content = text
                    if raw:
                        print("redis获取到的order_id", r.get("order_id"))
                        data = json.loads(raw)
                        bot.send_photo(data["chat_id"],
                                       saved_imgs_file_id[0],
                                       reply_to_message_id=data["message_id"],
                                       caption=f'''单号：{data['order_id']},{text_content}'''
                                       )
                else:
                    print("redis没有找到值")

    elif videos:
        print("视频 ")
        message = videos[0]
        text = message.caption
        if text is not None:
            llm_res = ask_llm(text)
            if llm_res == '9':
                print("代付冲正")
                # 代付冲正
                payout_reversal(message)
            else:
                country_name = ask_llm_re_country_name(message.chat.title)
                try:
                    data_address = json.loads(country_name)
                except json.JSONDecodeError:
                    print("不是 JSON，原始输出：", country_name)
                    data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
                print("country_name", country_name)
                if country_name != "无":
                    saved_vids_file_id = []
                    file_id = message.video.file_id
                    saved_vids_file_id.append(file_id)
                    filename = f"{timestamp}_viedo.mp4"
                    save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/videos"
                    # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\videos"
                    save_path = save_file(save_dir, file_id, filename)
                    print("data_address", data_address)
                    order_ids = ask_llm20_1(text)
                    order_data_ids = parse_order_ids(order_ids)
                    print("order_id:", order_data_ids['order_ids'][0])
                    data_payoutOrder = get_payment_inquiry_img(data_address, order_data_ids['order_ids'][0])
                    print("data_payoutOrder", data_payoutOrder)
                    try:
                        parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
                    except json.JSONDecodeError:
                        print("不是 JSON，原始输出：", data_payoutOrder)
                        parsed = {"status": 201}  # 先把 JSON 字符串转成字

                    vid_utr = ask_qwen_video_utr(save_path)

                    if data_address['address'] != "":
                        if parsed['status'] == 200:
                            order_sn = parsed['data']['orderInfo']['order_sn']
                            trade_sn = parsed['data']['orderInfo']['trade_sn']
                            amount = parsed['data']['orderInfo']['amount']
                            timestamp = parsed['data']['orderInfo']['instime']
                            dt = datetime.datetime.fromtimestamp(timestamp)
                            order_time = dt.strftime("%Y/%m/%d %H:%M:%S")
                            print("utr", vid_utr)

                            if parsed['data']['orderInfo']['status'] == 1 or parsed['data']['orderInfo']['status'] == 3:
                                bot.reply_to(message, f'''
                                    成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                            ''')
                                print("成功的无需补单操作")
                            else:
                                make_up_order = json.loads(
                                    get_payment_inquiry_openmakeup(data_address, order_data_ids['order_ids'][0], vid_utr))
                                print("make_up_order", make_up_order)
                                print("utr", vid_utr)
                                l = len(parsed['data']['orderInfo']['sourceOrders'])
                                if make_up_order['status'] == 200:
                                    bot.reply_to(message, f'''
                                        订单补单成功\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"订单补单成功"}\n订单时间:{order_time}
                                                            ''')
                                    print("订单补单成功")
                                if make_up_order['status'] == 17510:
                                    bot.reply_to(message, f'''
                                        订单状态错误\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"订单状态错误"}\n订单时间:{order_time}
                                                            ''')
                                    print("订单状态错误")
                                if make_up_order['status'] == 17511:
                                    bot.reply_to(message, f'''
                                        SYSTEM_EXCEPT_ERROR\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"SYSTEM_EXCEPT_ERROR"}\n订单时间:{order_time}
                                                            ''')
                                    print("SYSTEM_EXCEPT_ERROR")
                                if make_up_order['status'] == -2:
                                    bot.reply_to(message, f'''
                                        查询状态为空\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"查询状态为空"}\n订单时间:{order_time}
                                                            ''')
                                    print("查询状态为空")

                                if l != 0:
                                    if make_up_order['status'] == 10001:
                                        bot.reply_to(message, f'''
                                            已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"暂未收到"}\n订单时间:{order_time}
                                                            ''')
                                        group_chat_id = -4805059187
                                        # 发送图片
                                        upstream = parsed['data']['orderInfo']['sourceOrders'][l - 1]['order_ref']
                                        data1 = {
                                            "chat_id": message.chat.id,
                                            "message_id": message.message_id,
                                            "order_id": order_data_ids['order_ids'][0]
                                        }
                                        r.set(upstream, json.dumps(data1), ex=2592000)
                                        bot.send_video(group_chat_id,
                                                       saved_vids_file_id[0],
                                                       caption=f'''单号：{upstream}\n麻烦核查下是否收到款项，如若未收到，请识别是否是你们的收款账户？'''
                                                       )
                                        # with open(save_path, "rb") as f:
                                        #     bot.send_video(group_chat_id,
                                        #                f,
                                        #                caption=f'''单号：{upstream}\n麻烦核查下是否收到款项，如若未收到 请识别是否是你们的收款账户？'''
                                        #                    )
                                        print("请联系上游")
                                else:
                                    bot.reply_to(message, "没有上游订单号")
                                    print("没有上游订单号")
                        else:
                            bot.reply_to(message, "订单号不正确或者订单号不存在，请重新查看。")
                            print("接口调不通，请重新查看接口。")
                    else:
                        bot.reply_to(message, "没有提取到国家名称，需要请重新发一下")
                        print("没有提取到国家名称，需要请重新发一下")
                else:
                    # 1. 是否回复了消息
                    saved_vids_file_id = []
                    file_id = message.video.file_id
                    saved_vids_file_id.append(file_id)
                    filename = f"{timestamp}_viedo.mp4"
                    save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/videos"
                    # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\videos"
                    save_path = save_file(save_dir, file_id, filename)
                    if hasattr(message, "reply_to_message") and message.reply_to_message:
                        if message.reply_to_message.caption is not None:
                            order_ids = ask_llm20_1(message.reply_to_message.caption)
                            order_ids_data = parse_order_ids(order_ids)
                            raw = r.get(order_ids_data['order_ids'][0])
                            if text is None:
                                text_content = ""
                            else:
                                text_content = text
                            if raw:
                                data = json.loads(raw)
                                bot.send_video(data["chat_id"],
                                               saved_vids_file_id[0],
                                               reply_to_message_id=data["message_id"],
                                               caption=f'''单号：{data['order_id']},{text_content}'''
                                               )
                        elif message.reply_to_message.text is not None:
                            order_ids = ask_llm20_1(message.reply_to_message.text)
                            order_ids_data = parse_order_ids(order_ids)
                            raw = r.get(order_ids_data['order_ids'][0])
                            if text is None:
                                text_content = ""
                            else:
                                text_content = text
                            if raw:
                                data = json.loads(raw)
                                bot.send_video(data["chat_id"],
                                               saved_vids_file_id[0],
                                               reply_to_message_id=data["message_id"],
                                               caption=f'''单号：{data['order_id']},{text_content}'''
                                               )
                        else:
                            print("redis没有找到值")
        else:
            print("没有文字，只有视频的回复上游消息")
            saved_vids_file_id = []
            file_id = message.video.file_id
            saved_vids_file_id.append(file_id)
            filename = f"{timestamp}_viedo.mp4"
            save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/videos"
            # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\videos"
            save_path = save_file(save_dir, file_id, filename)

            # 1. 是否回复了消息
            if hasattr(message, "reply_to_message") and message.reply_to_message:
                if message.reply_to_message.caption is not None:
                    order_ids = ask_llm20_1(message.reply_to_message.caption)
                    order_ids_data = parse_order_ids(order_ids)
                    raw = r.get(order_ids_data['order_ids'][0])
                    if text is None:
                        text_content = ""
                    else:
                        text_content = text
                    if raw:
                        data = json.loads(raw)
                        bot.send_video(data["chat_id"],
                                       saved_vids_file_id[0],
                                       reply_to_message_id=data["message_id"],
                                       caption=f'''单号：{data['order_id']},{text_content}'''
                                       )
                elif message.reply_to_message.text is not None:
                    order_ids = ask_llm20_1(message.reply_to_message.text)
                    order_ids_data = parse_order_ids(order_ids)
                    raw = r.get(order_ids_data['order_ids'][0])
                    if text is None:
                        text_content = ""
                    else:
                        text_content = text
                    if raw:
                        data = json.loads(raw)
                        bot.send_video(data["chat_id"],
                                       saved_vids_file_id[0],
                                       reply_to_message_id=data["message_id"],
                                       caption=f'''单号：{data['order_id']},{text_content}'''
                                       )
                else:
                    print("redis没有找到值")
    elif animations:
        print("视频 1")
        saved_anims_file_id = []
        message = animations[0]
        print("animations[0]", animations[0])
        text = message.caption
        llm_res = ask_llm(text)
        if llm_res == '9':
            print("代付冲正")
            # 代付冲正
            payout_reversal_anim(message)
        else:
            country_name = ask_llm_re_country_name(message.chat.title)
            try:
                data_address = json.loads(country_name)
            except json.JSONDecodeError:
                print("不是 JSON，原始输出：", country_name)
                data_address = {"address": "", "mid": ""}  # 兜底，直接包一层
            print("country_name", country_name)
            if country_name != "无":
                file_id = message.animation.file_id
                saved_anims_file_id.append(file_id)
                filename = f"{timestamp}_viedo.mp4"
                save_dir = rf"/home/admin/data/data/aicustomer-service/source_files/videos"
                # save_dir = "D:\\yuanbei\\客服问答机器人需求表\\source_files\\videos"
                save_path = save_file(save_dir, file_id, filename)
                text = message.caption
                print("data_address", data_address)
                order_ids = ask_llm20_1(text)
                order_data_ids = parse_order_ids(order_ids)
                print("order_id:", order_data_ids['order_ids'][0])
                data_payoutOrder = get_payment_inquiry_pdf(data_address, order_data_ids['order_ids'][0])
                print("data_payoutOrder", data_payoutOrder)
                try:
                    parsed = json.loads(data_payoutOrder)  # 先把 JSON 字符串转成字典
                except json.JSONDecodeError:
                    print("不是 JSON，原始输出：", data_payoutOrder)
                    parsed = {"status": 201}  # 先把 JSON 字符串转成字

                vid_utr = ask_qwen_video_utr(save_path)
                if vid_utr is not None:
                    data1 = {
                        "chat_id": message.chat.id,
                        "message_id": message.message_id,
                    }
                    r.set("1", json.dumps(data1), ex=2592000)

                if data_address['address'] != "":
                    if parsed['status'] == 200:
                        order_sn = parsed['data']['orderInfo']['order_sn']
                        trade_sn = parsed['data']['orderInfo']['trade_sn']
                        amount = parsed['data']['orderInfo']['amount']
                        timestamp = parsed['data']['orderInfo']['instime']
                        vid_utr = ask_qwen_video_utr(save_path)
                        dt = datetime.datetime.fromtimestamp(timestamp)
                        order_time = dt.strftime("%Y/%m/%d %H:%M:%S")
                        print("utr", vid_utr)

                        if parsed['data']['orderInfo']['status'] == 1 or parsed['data']['orderInfo']['status'] == 3:
                            bot.reply_to(message, f'''
                                成功的无需补单操作\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"成功的无需补单操作"}\n订单时间:{order_time}
                                                        ''')
                            print("成功的无需补单操作")
                        else:
                            make_up_order = json.loads(
                                get_payment_inquiry_openmakeup(data_address, order_data_ids['order_ids'][0], vid_utr))
                            print("make_up_order", make_up_order)
                            print("utr", vid_utr)
                            l = len(parsed['data']['orderInfo']['payoutSourceOrders'])
                            if make_up_order['status'] == 200:
                                bot.reply_to(message, f'''
                                    订单补单成功\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"订单补单成功"}\n订单时间:{order_time}
                                                        ''')
                                print("订单补单成功")
                            if make_up_order['status'] == 17510:
                                bot.reply_to(message, f'''
                                    订单状态错误\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"订单状态错误"}\n订单时间:{order_time}
                                                        ''')
                                print("订单状态错误")
                            if make_up_order['status'] == 17511:
                                bot.reply_to(message, f'''
                                    SYSTEM_EXCEPT_ERROR\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"SYSTEM_EXCEPT_ERROR"}\n订单时间:{order_time}
                                                        ''')
                                print("SYSTEM_EXCEPT_ERROR")
                            if make_up_order['status'] == -2:
                                bot.reply_to(message, f'''
                                    查询状态为空\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"查询状态为空"}\n订单时间:{order_time}
                                                        ''')
                                print("查询状态为空")

                            if l != 0:
                                if make_up_order['status'] == 10001:
                                    bot.reply_to(message, f'''
                                        已反馈核查，有最新结果同步您\n\nDeepay单号：{order_sn}\n商户单号：{trade_sn}\n流水号：{vid_utr}\n订单金额：{amount}\n状态：{"暂未收到"}\n订单时间:{order_time}
                                                        ''')
                                    group_chat_id = -4805059187
                                    # 发送图片
                                    upstream = parsed['data']['orderInfo']['sourceOrders'][l - 1]['order_ref']
                                    data1 = {
                                        "chat_id": message.chat.id,
                                        "message_id": message.message_id,
                                        "order_id": order_data_ids['order_ids'][0]
                                    }
                                    r.set(upstream, json.dumps(data1), ex=2592000)
                                    bot.send_video(group_chat_id,
                                                   saved_anims_file_id[0],
                                                   caption=f'''单号：{upstream}\n麻烦核查下是否收到款项，如若未收到，请识别是否是你们的收款账户？'''
                                                   )
                                    # with open(save_path, "rb") as f:
                                    #     bot.send_video(group_chat_id,
                                    #                f,
                                    #                caption=f'''单号：{upstream}\n麻烦核查下是否收到款项，如若未收到 请识别是否是你们的收款账户？'''
                                    #                    )
                                    print("请联系上游")
                            else:
                                bot.reply_to(message, "没有上游订单号")
                                print("没有上游订单号")
                    else:
                        bot.reply_to(message, "订单号不正确或者订单号不存在，请重新查看。")
                        print("接口调不通，请重新查看接口。")
                else:
                    bot.reply_to(message, "没有提取到国家名称，需要请重新发一下")
                    print("没有提取到国家名称，需要请重新发一下")
            else:
                # 1. 是否回复了消息
                if hasattr(message, "reply_to_message") and message.reply_to_message:
                    if message.reply_to_message.caption is not None:
                        order_ids = ask_llm20_1(message.reply_to_message.caption)
                        order_ids_data = parse_order_ids(order_ids)
                        raw = r.get(order_ids_data['order_ids'][0])
                        if text is None:
                            text_content = ""
                        else:
                            text_content = text
                        if raw:
                            data = json.loads(raw)
                            bot.send_video(data["chat_id"],
                                           saved_anims_file_id[0],
                                           reply_to_message_id=data["message_id"],
                                           caption=f'''单号：{data['order_id']},{text_content}'''
                                           )
                    elif message.reply_to_message.text is not None:
                        order_ids = ask_llm20_1(message.reply_to_message.text)
                        order_ids_data = parse_order_ids(order_ids)
                        raw = r.get(order_ids_data['order_ids'][0])
                        if text is None:
                            text_content = ""
                        else:
                            text_content = text
                        if raw:
                            data = json.loads(raw)
                            bot.send_video(data["chat_id"],
                                           saved_anims_file_id[0],
                                           reply_to_message_id=data["message_id"],
                                           caption=f'''单号：{data['order_id']},{text_content}'''
                                           )
                    else:
                        print("redis没有找到值")


@bot.message_handler(content_types=['photo', 'video', 'document', 'animation'])
def handle_media(message):
    print("收到消息:", message.content_type)

    # 如果没有 group_id，说明是单条消息（单张图片或单个视频）
    group_id = message.media_group_id or message.message_id

    if group_id not in media_cache:
        media_cache[group_id] = {"photos": [], "videos": [], "animations": []}
        # 启动定时器，延迟1s 再处理，确保同一个相册的所有消息都收齐
        threading.Timer(1.0, process_group, args=(group_id,)).start()

    # 收集消息
    if message.content_type == "photo":
        media_cache[group_id]["photos"].append(message)
    elif message.content_type == "video":
        media_cache[group_id]["videos"].append(message)
    elif message.content_type == "animation":
        # 动图（GIF，但以 mp4 格式保存）
        media_cache[group_id]["animations"].append(message)


# 启动 Bot
print("🤖 Bot 正在运行...")
bot.polling(none_stop=True)
